package com.ruoyi.system.controller;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.AsyncHandler;

import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.constant.SchoolConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.utils.send.SendUtils;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.InnerAuth;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.security.utils.SecurityUtils;

import com.ruoyi.common.utils.uuid.VerificationCode;
import com.ruoyi.system.domain.SchoolRoleApproveLog;
import com.ruoyi.system.domain.vo.IndexSchoolRole;
import com.ruoyi.system.service.ISchoolRoleApproveLogService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import jdk.nashorn.api.scripting.ScriptUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.TimeoutUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import com.ruoyi.system.domain.SchoolRole;
import com.ruoyi.system.service.ISchoolRoleService;


/**
 * 学校角色增删改查Controller
 * 
 * @author hyb
 * @date 2023-02-02
 */
@Transactional(rollbackFor = Exception.class)
@RestController
@RequestMapping("/schoolRole/schoolRole")
public class SchoolRoleController extends BaseController
{
    @Autowired
    private ISchoolRoleService schoolRoleService;

    @Autowired
    ISysUserService userService;

    @Autowired
    ISchoolRoleApproveLogService schoolRoleApproveLogService;

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @Value("${spring.mail.username}")
    private String mail;

    @Autowired
    ISysConfigService configService;
    /*
    * 发送验证码,五分钟有效
    * */

    @Log(title = "发送验证码", businessType = BusinessType.INSERT)
    @PostMapping("/send")
    public AjaxResult send(@RequestParam("email")String email) throws Exception {

        if (StringUtils.isEmpty(email)){
            return AjaxResult.error("邮箱不能为空");
        }
        Long userId = SecurityUtils.getUserId();
        //六十秒之内不能发送
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(SchoolConstants.APPROVE_CODE_SEND_KEY + userId,"1", 60, TimeUnit.SECONDS);
        if (Boolean.TRUE.equals(aBoolean)){
            //发送
            String letter = VerificationCode.getLetter(6);

            String s = configService.selectConfigByKey(Constants.SCHOOL_CODE_SYS_KEY);

            redisTemplate.opsForValue().set(SchoolConstants.APPROVE_CODE_KEY+userId,letter,Integer.parseInt(s),TimeUnit.MINUTES);
            SendUtils.sendHtmlEmail(mail,email,"学生认证邮箱校验码", letter);
        }else{
            return AjaxResult.error("六十秒之内不能发送");
        }

        return AjaxResult.success();
    }



    @Log(title = "学校角色增删改查", businessType = BusinessType.INSERT)
    @PostMapping("/front")
    public AjaxResult addFront(@RequestBody SchoolRole schoolRole)
    {

        Long userId = SecurityUtils.getUserId();
        //首先校验验证码
        String code=schoolRole.getCode();
        if (StringUtils.isEmpty(code)){
            return AjaxResult.error("验证码不能为空");
        }
        String s = redisTemplate.opsForValue().get(SchoolConstants.APPROVE_CODE_KEY + userId);

        if (StringUtils.isEmpty(s)){
            return AjaxResult.error("验证码已过期");
        }

        if (!code.equalsIgnoreCase(s)){
            return AjaxResult.error("验证码不正确");
        }


        SchoolRole roe = new SchoolRole();
        roe.setUserId(SecurityUtils.getUserId());
        List<SchoolRole> schoolRoles = schoolRoleService.selectSchoolRoleList(roe);

        if (schoolRoles.size()!=0){
            return AjaxResult.error("该用户已存在认证,无法修改");
        }
        schoolRole.setIdcard(SecurityUtils.encryptPassword(schoolRole.getIdcard()));
        schoolRole.setUserId(SecurityUtils.getUserId());

        schoolRoleService.insertSchoolRole(schoolRole);

        //插入审核记录
        SchoolRoleApproveLog schoolRoleApproveLog = new SchoolRoleApproveLog();
        Date nowDate = DateUtils.getNowDate();

        String username = SecurityUtils.getUsername();
        SchoolRole schoolRole1 = new SchoolRole();
        schoolRole1.setUserId(userId);
        List<SchoolRole> roleList = schoolRoleService.selectSchoolRoleList(schoolRole1);
        schoolRoleApproveLog.setCreateTime(nowDate);
        schoolRoleApproveLog.setToApproveTime(nowDate);
        schoolRoleApproveLog.setToApproveUserId(userId);
        schoolRoleApproveLog.setToApproveUserName(username);
        schoolRoleApproveLog.setSchoolRoleId(schoolRole.getId());
        schoolRoleApproveLog.setToApproveRealName(roleList.size()==0?"":roleList.get(0).getName());
        schoolRoleApproveLogService.insertSchoolRoleApproveLog(schoolRoleApproveLog);

        return AjaxResult.success();
    }

    /*
     * 审核认证信息
     * */
    @PostMapping("/approve")
    public AjaxResult approve(
            @RequestParam("id")Long id,
            @RequestParam("status")String status,
            @RequestParam("note")String note){

        if (id==null) return AjaxResult.error();



        //修改审核状态
        SchoolRole schoolRole = new SchoolRole();
        schoolRole.setId(id);
        schoolRole.setPreparefield2(status);

        //查询状态是否为0,为0可以审核
        SchoolRole schoolRoleById = schoolRoleService.selectSchoolRoleById(id);
        if (schoolRoleById.getPreparefield2().equals(SchoolConstants.APPROVE_SUCCESS)){
            return AjaxResult.error("已审核成功,无需再审核");
        }

        schoolRoleService.updateSchoolRole(schoolRole);


        //修改审核记录
        SchoolRoleApproveLog schoolRoleApproveLog = new SchoolRoleApproveLog();
        schoolRoleApproveLog.setPf1(status);
        schoolRoleApproveLog.setSchoolRoleId(id);
        schoolRoleApproveLog.setApproveTime(DateUtils.getNowDate());
        schoolRoleApproveLog.setApproveUserId(SecurityUtils.getUserId());
        schoolRoleApproveLog.setApproveUserName(SecurityUtils.getUsername());
        SchoolRole role = new SchoolRole();
        role.setUserId(SecurityUtils.getUserId());
        List<SchoolRole> schoolRoles = schoolRoleService.selectSchoolRoleList(role);
        String realName=schoolRoles.size()==0?"":schoolRoles.get(0).getName();
        schoolRoleApproveLog.setApproveRealName(realName);
        schoolRoleApproveLog.setSchoolRoleId(id);
        schoolRoleApproveLog.setUpdateTime(DateUtils.getNowDate());
        schoolRoleApproveLogService.updateSchoolRoleApproveLogByRoleId(schoolRoleApproveLog);

        return AjaxResult.success();

    }



    @GetMapping("/getPersonal")
    public AjaxResult getPersonal(){

        SchoolRole schoolRole = new SchoolRole();
        schoolRole.setUserId(SecurityUtils.getUserId());
        List<SchoolRole> schoolRoles = schoolRoleService.selectSchoolRoleList(schoolRole);
        return AjaxResult.success().put("user",schoolRoles.get(0));

    }

    @InnerAuth
    @GetMapping("/getPersonal/inner")
    public AjaxResult getPersonalInner(){

        SchoolRole schoolRole = new SchoolRole();
        schoolRole.setUserId(SecurityUtils.getUserId());
        List<SchoolRole> schoolRoles = schoolRoleService.selectSchoolRoleList(schoolRole);
        return AjaxResult.success().put("user",schoolRoles.get(0));

    }

    @InnerAuth
    @GetMapping("/inner/getPersonalSchoolRole")
    public R<SchoolRole> getPersonalSchoolRole(@RequestParam("userId")Long userId){
        SchoolRole schoolRole = new SchoolRole();
        schoolRole.setId(userId);
        List<SchoolRole> list = schoolRoleService.selectSchoolRoleList(schoolRole);
        return R.ok(list.size()==0?null:list.get(0));
    }

    /*
    * 根据账号的部门id查询指导老师
    * */
    @GetMapping("/getTeacherBySystemDeptId")
    public AjaxResult getTeacherBySystemDeptId(){
        Long deptId = userService.selectUserById(SecurityUtils.getUserId()).getDeptId();
        List<SchoolRole> list = schoolRoleService.selectSchoolRoleListBySystemDeptId(deptId);
        return AjaxResult.success().put("data",list);
    }

    /**
     * 查询学校角色增删改查列表
     */
    @RequiresPermissions("schoolRole:schoolRole:list")
    @GetMapping("/list")
    public TableDataInfo list(SchoolRole schoolRole)
    {
        if (schoolRole.getIdcard()!=null){
            schoolRole.setIdcard(SecurityUtils.encryptPassword(schoolRole.getIdcard()));
        }
        startPage();
        List<SchoolRole> list = schoolRoleService.selectSchoolRoleList(schoolRole);
        return getDataTable(list);
    }

    /**
     * 导出学校角色增删改查列表
     */
    @RequiresPermissions("schoolRole:schoolRole:export")
    @Log(title = "学校角色增删改查", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SchoolRole schoolRole)
    {
        List<SchoolRole> list = schoolRoleService.selectSchoolRoleList(schoolRole);
        ExcelUtil<SchoolRole> util = new ExcelUtil<SchoolRole>(SchoolRole.class);
        util.exportExcel(response, list, "学校角色增删改查数据");
    }

    /**
     * 获取学校角色增删改查详细信息
     */
    @RequiresPermissions("schoolRole:schoolRole:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(schoolRoleService.selectSchoolRoleById(id));
    }

    @InnerAuth
    @GetMapping(value = "/innerInfo")
    public AjaxResult getInnerInfo(@RequestParam("id") Long id)
    {
        IndexSchoolRole schoolRole = schoolRoleService.selectSchoolRoleAndSysUserById(id);
        return success().put("role",schoolRole);
    }

    /**
     * 新增学校角色增删改查
     */
    @RequiresPermissions("schoolRole:schoolRole:add")
    @Log(title = "学校角色增删改查", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SchoolRole schoolRole)
    {
        return toAjax(schoolRoleService.insertSchoolRole(schoolRole));
    }


    /**
     * 修改学校角色增删改查
     */
    @RequiresPermissions("schoolRole:schoolRole:edit")
    @Log(title = "学校角色增删改查", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SchoolRole schoolRole)
    {
        return toAjax(schoolRoleService.updateSchoolRole(schoolRole));
    }

    /**
     * 删除学校角色增删改查
     */
    @RequiresPermissions("schoolRole:schoolRole:remove")
    @Log(title = "学校角色增删改查", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(schoolRoleService.deleteSchoolRoleByIds(ids));
    }
}
